/**
 * fengbin 2007-11-29
 */
package com.wsj.util.tool;

import java.text.MessageFormat;
import java.util.Date;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author fengbin
 *
 * create date:2007-11-29
 * 
 * 邮件发送
 * 
 * 
 * 备注:传入用户名,和注册者的邮件地址,就可以发送邮件了
 */
public class SendEmailUtil {
	
	private static Log logger = LogFactory.getLog(SendEmailUtil.class);
	//接受邮件的email
	private String reciveEmail;

	//邮件内容
	private String content;
	//用户名
	private String userPassprotsName;
	//注册的email
	private String email;
	
	//邮件信息
	private String messages;
	//邮件服务器:smtp.sohu.com
	private String mailserver;
	//服务器邮件:efzkadmin_2007@sohu.com
	private String from;
	//主题
	private String subject;
	//服务器邮件用户名
	private String fromname;
	//服务器邮件密码
	private String frompass;
	
	//开始日期
	private Date timeXX;
	//结束日期
    private  Date timeSX;
    
    //配置文件
    private String configFilePath="getPassword";
    
    //找会密码的用户名
    private String findPasswordUsername;
    //找回密码的邮件
    private String findPasswordEmail;
    
    //报错信息[0]用户名不能为空,[1]电子邮件不能为空,[2]验证码,[3]是否成功
    private String[] msg={"","","",""};
    
    private String checkCode;
    

	/**
	 * 发送邮件
	 * p_userPasswordsName 用户名
	 * p_reciveEmail 接受邮件的地址
	 *
	 */
	public boolean sendEmail(String p_userPasswordsName,String p_reciveEmail)
	{
		boolean sendOk=false; //发送邮件是否成功
	
			try {
				
						//获取配置文件中的信息=
						loadMailMessageFromConfigFile(configFilePath);
						
						//设置邮件服务器
						Properties mailProps = new Properties();
						mailProps.put("mail.smtp.host", mailserver);
						mailProps.put("mail.smtp.auth", "true");
						// 创建 session
						Session mailSession = Session.getInstance(mailProps,new PasswordAuthenticator("efzkadmin_2007","efzk2007"));
				
						// 创建 邮件的message，message对象包含了邮件众多有的部件，都是封装成了set方法去设置的
						MimeMessage message = null;
						Transport transport = null;
						message = new MimeMessage(mailSession);
					
					
					
						//设置发信人
						message.setFrom(new InternetAddress(from));
						//主题
						message.setSubject(subject);
						
						Multipart mp = new MimeMultipart();
						BodyPart bp = new MimeBodyPart();
						//创建正文
						String content=this.createContent(p_userPasswordsName);
						bp.setContent(content,"text/html;charset=UTF-8");
						mp.addBodyPart(bp);
						
						message.setContent(mp);
						transport = mailSession.getTransport("smtp");
			
			//			transport.connect(ManageUserConstent.strHost, ManageUserConstent.strUserName, ManageUserConstent.strPassword);
						
						transport.connect(mailserver, fromname,frompass);
						
						message.setRecipient(Message.RecipientType.TO, new InternetAddress(p_reciveEmail));
						//发送邮件
						transport.sendMessage(message, message.getAllRecipients());
							
						sendOk=true;
			             logger.error("发送邮件成功!");
			} catch (Exception e) {
				logger.error("发送邮件失败,异常抛出!");
				e.printStackTrace();
			}
		
		return sendOk;
	}
	
	
	/****
	 * 发送多个参数的邮件
	 * @param p_userPasswordsName
	 * @param p_reciveEmail
	 * @return
	 */
	public boolean sendEmailForManyParam(String[] contents,String p_reciveEmail)
	{
		boolean sendOk=false; //发送邮件是否成功
	
			try {
				
						//获取配置文件中的信息=
						loadMailMessageFromConfigFile(configFilePath);
						
						//设置邮件服务器
						Properties mailProps = new Properties();
						mailProps.put("mail.smtp.host", mailserver);
						mailProps.put("mail.smtp.auth", "true");
						// 创建 session
						Session mailSession = Session.getInstance(mailProps,new PasswordAuthenticator("efzkadmin_2007","efzk2007"));
				
						// 创建 邮件的message，message对象包含了邮件众多有的部件，都是封装成了set方法去设置的
						MimeMessage message = null;
						Transport transport = null;
						message = new MimeMessage(mailSession);
					
					
					
						//设置发信人
						message.setFrom(new InternetAddress(from));
						//主题
						message.setSubject(subject);
						
						Multipart mp = new MimeMultipart();
						BodyPart bp = new MimeBodyPart();
						//创建正文
						String content=this.createContentForManyParam(contents);
						bp.setContent(content,"text/html;charset=UTF-8");
						mp.addBodyPart(bp);
						
						message.setContent(mp);
						transport = mailSession.getTransport("smtp");
			
			//			transport.connect(ManageUserConstent.strHost, ManageUserConstent.strUserName, ManageUserConstent.strPassword);
						
						transport.connect(mailserver, fromname,frompass);
						
						message.setRecipient(Message.RecipientType.TO, new InternetAddress(p_reciveEmail));
						//发送邮件
						transport.sendMessage(message, message.getAllRecipients());
							
						sendOk=true;
			             logger.error("发送邮件成功!");
			} catch (Exception e) {
				logger.error("发送邮件失败,异常抛出!");
				e.printStackTrace();
			}
		
		return sendOk;
	}
	
	
	/****
	 * 获取多个参数的内容
	 * @param passwordsName
	 * @return
	 */
	private String createContentForManyParam(String[] passwordsName) 
	{
		 StringBuffer retContent=new StringBuffer("<meta http-equiv=content-type content=text/html; charset=UTF-8>");
		  MessageFormat messageformat = new MessageFormat("");
	        messageformat.applyPattern(messages);
	        String model = messageformat.format(((Object) (passwordsName)));
		  retContent=retContent.append(model);
		  return retContent.toString();
	}


	/***
	 * 通过用户名获取密码对象
	 * 用户名 + "," + 密码
	 * @return
	 * 
	 */
	public String[] loadUserPassword(String userPassprot)
	{
		String[] temp = new String[2];
		//需要填充
		temp = userPassprot.split(",");
		//测试
		return temp;
	}
	
	/***
	 * 通过用户名组合内容
	 */
	public String createContent(String userPasswordsName)
	{
	  String retContent="<meta http-equiv=content-type content=text/html; charset=UTF-8>";
	  //用户名和密码数组
	  String[] usernameAndPassword=new String[2];
	  //获取用户密码
	  usernameAndPassword = this.loadUserPassword(userPasswordsName);
	  usernameAndPassword[0] = usernameAndPassword[0];
	  usernameAndPassword[1] = usernameAndPassword[1];
	  //获取模板
	  String model = this.defineSendModelNew(usernameAndPassword);
	  retContent=retContent+model;
	  return retContent;
	}
	
	/***
	 * 使用配置文件获取模板信息
	 */
	public String defineSendModelNew(String[] importantMessage)
	{
	        Object aobj[] = { importantMessage[0], importantMessage[1]};
	        MessageFormat messageformat = new MessageFormat("");
	        messageformat.applyPattern(messages);
	        String s = messageformat.format(((Object) (aobj)));
	      return s;
	}
	
	
	/**
	 * 读取配置文件，获得发送的信息,
	 * 
	 */
	public void loadMailMessageFromConfigFile(String s)
    {
		ResourceBundle rb = ResourceBundle.getBundle(s);
		//信息
        messages = rb.getString("message");
        //邮件服务器
        mailserver = rb.getString("mailserver");
        //来自
        from = rb.getString("from");
        //主题
        subject = rb.getString("subject");
        //发送邮件用户名
        fromname = rb.getString("fromname");
        //发送邮件密码
        frompass = rb.getString("frompass");
           
        
    }
	
	
	public String getReciveEmail() {
		return reciveEmail;
	}
	public void setReciveEmail(String reciveEmail) {
		this.reciveEmail = reciveEmail;
	}


	public String getContent() {
		return content;
	}


	public void setContent(String content) {
		this.content = content;
	}




	public String getEmail() {
		return email;
	}



	public void setEmail(String email) {
		this.email = email;
	}





	public Date getTimeSX() {
		return timeSX;
	}



	public void setTimeSX(Date timeSX) {
		this.timeSX = timeSX;
	}



	public Date getTimeXX() {
		return timeXX;
	}



	public void setTimeXX(Date timeXX) {
		this.timeXX = timeXX;
	}


	public String getUserPassprotsName() {
		return userPassprotsName;
	}



	public void setUserPassprotsName(String userPassprotsName) {
		this.userPassprotsName = userPassprotsName;
	}

	public String getFindPasswordEmail() {
		return findPasswordEmail;
	}
	public void setFindPasswordEmail(String findPasswordEmail) {
		this.findPasswordEmail = findPasswordEmail;
	}
	public String getFindPasswordUsername() {
		return findPasswordUsername;
	}
	public void setFindPasswordUsername(String findPasswordUsername) {
		this.findPasswordUsername = findPasswordUsername;
	}
	public String[] getMsg() {
		return msg;
	}
	public void setMsg(String[] msg) {
		this.msg = msg;
	}
	public String getCheckCode() {
		return checkCode;
	}
	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}



	public String getConfigFilePath() {
		return configFilePath;
	}



	public void setConfigFilePath(String configFilePath) {
		this.configFilePath = configFilePath;
	}
	
	



}



/**
 * 用户名和密码类
 * @author fengbin
 *
 * create date:2007-11-29
 */
class PasswordAuthenticator extends Authenticator {

    private String username;
    private String password;

    public PasswordAuthenticator(String username, String password) {
        this.username = username;
        this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }

}
